import Logger from '@joplin/utils/Logger';
import { commandToString, execCommand } from '@joplin/utils';
import { WorkHandler } from '../types';

const logger = Logger.create('HtrCli');

export default class HtrCli implements WorkHandler {

	private htrCliDockerImage: string;
	private htrCliImagesFolder: string;

	public constructor(htrCliDockerImage: string, htrCliImagesFolder: string) {
		this.htrCliDockerImage = htrCliDockerImage;
		this.htrCliImagesFolder = htrCliImagesFolder;
	}

	public async init() {
		logger.info('Loading');
		const result = await execCommand(['docker', 'pull', this.htrCliDockerImage], { quiet: true });
		logger.info('Finished loading: ', result);
	}

	public async run(imageName: string) {
		const command = ['docker', 'run', '--rm', '-t', '-v', `${this.htrCliImagesFolder}:/images`, this.htrCliDockerImage, imageName];

		logger.info('Running transcription...');
		logger.info(`Command: ${commandToString(command[0], command.slice(1))}`);
		const result = await execCommand(command, { quiet: true });

		logger.info('Finished transcription');
		return this.cleanUpResult(result);
	}

	public cleanUpResult(transcriptionAndLogs: string) {
		const s1 = transcriptionAndLogs.split(/image decoded.*/);
		// Before the last `image decoded` line it is all logs generated by the transcription tool
		const everythingAfterImageDecoded = (s1[s1.length - 1]).trim();
		// After the transcription there are still some logs from the transcription tool
		const removedLastLogs = everythingAfterImageDecoded.slice(0, everythingAfterImageDecoded.indexOf('llama_perf_context_print:'));
		// Model is instructed to put transcription inside triple backticks
		return removedLastLogs.replace(/```/g, '').trim();
	}
}
